import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import NproGress from 'nprogress'
import { message } from 'antd'
import 'nprogress/nprogress.css'
import list from './list'

axios.defaults.baseURL = "/api"
axios.defaults.timeout = 30000

interface IAuth {
    headers: {
        Authorization: string | undefined | null
    }
}

type AxiosAllConfig = IAuth | AxiosRequestConfig

axios.interceptors.request.use((config: AxiosAllConfig) => {
    if (config.headers) {
        config.headers.Authorization = sessionStorage.getItem('token')? sessionStorage.getItem('token'): ''
    }
    NproGress.start()
    return config
})


axios.interceptors.response.use((data: AxiosResponse) => {
    NproGress.done()
    
    const index = list.findIndex(item => (data.config.url? data.config.url.includes(item.url): '') && (data.config.method === item.method))
    
    if (index !== -1) {
        if (data.data.message) {
            message.success(data.data.message)
        } else {
            message.success(list[index].message)
        }
    }
    return data
}, (err) => {
    if (err.response) {
        switch(err.response.status) {
            case 422:
                message.error("缺少参数")
                break
        }
    }
})

export default axios